import java.io.*;
import java.net.Socket;

/**
 * @License: (C) Copyright 2013-2022
 * @Contact: abcque@outlook.com
 * @IDE: IntelliJ IDEA
 * @Encoding: utf-8
 * @Project: st2214st2215
 * @Package: PACKAGE_NAME
 * @File: TCPCopyFileClient.java
 * @Time: 2023/5/23 14:34
 * @Author: abcque
 * @Description:
 * @Modifier:
 * @ModifyDate:
 * @ModifyRemark:
 */
public class TCPCopyFileClient {
    public static void main(String[] args) {
        try {
            Socket client = new Socket("127.0.0.1", 8888);
            System.out.println("客户端与服务器已经连接");

            String fileName = "abc.txt";

            // 打开输出流
            OutputStream outputStream = client.getOutputStream();
            // 发送文件名
            outputStream.write(fileName.getBytes());

            // 将文件内容通过网络进行传输
            File file = new File(fileName);
            long size = file.length();
            // 发送文件的大小
            outputStream.write(Long.toString(size).getBytes());

            FileInputStream fileInputStream = new FileInputStream(fileName);

            byte[] bytes = new byte[8192];
            int length;
            while ((length = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, length);
            }
            fileInputStream.close();
            System.out.println("文件发送完毕");


            byte[] inputTemp = new byte[8192];
            InputStream inputStream = client.getInputStream();
            length = inputStream.read(inputTemp);
            String info = new String(inputTemp, 0, length);
            System.out.println(info);

            inputStream.close();
            // 关闭输出流
            outputStream.close();
            // 关闭 Socket
            client.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
